﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace EasyFramework.MultiMedia
{
    /// <summary>
    /// Mp3播放辅助类
    /// from:http://www.cnblogs.com/studyplay/archive/2011/12/09/2281783.html
    /// todo:增加获取当前状态（播放、暂停）的方法
    /// </summary>
    public class Mp3Player
    {
        /// <summary>   
        /// 文件地址  
        /// </summary>
        public string FilePath;
        /// <summary>   
        /// 播放音乐  
        /// </summary>
        public void Play()
        {
            string tmepstr = "";
            tmepstr = tmepstr.PadLeft(128, Convert.ToChar(" "));
            mciSendString("close all", "", 0, 0);
            mciSendString("open " + FilePath + " alias media", tmepstr, tmepstr.Length, 0); mciSendString("play media", "", 0, 0);
        }

        /// <summary>   
        /// 暂停  
        /// </summary>
        public void Pause()
        {
            mciSendString("pause media", "", 0, 0);
        }

        /// <summary>   
        /// 停止  
        /// </summary>
        public void Stop()
        {
            mciSendString("close media", "", 0, 0);
        }
        /// <summary>   
        /// 继续播放  
        /// </summary>
        public void Resume()
        {
            string TemStr = "";
            TemStr = TemStr.PadLeft(128, Convert.ToChar(" "));
            mciSendString("resume media", TemStr, TemStr.Length, 0);
        }

        //获取音乐长度
        public int GetMusicLength
        {
            get
            {
                string durLength = "";
                durLength = durLength.PadLeft(128, Convert.ToChar(" "));
                mciSendString("status media length", durLength, durLength.Length, 0);
                durLength = durLength.Trim();
                if (durLength == "" || durLength == "\0") return 0;
                return (int)(Convert.ToDouble(durLength));
            }
        }
        /// <summary>   
        /// API函数  
        /// </summary>
        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        private static extern int mciSendString(
         string lpstrCommand,
         string lpstrReturnString,
         int uReturnLength,
         int hwndCallback
        );
    }
}